package cn.yuanqiao.archive.detection.service.impl;

import cn.yuanqiao.archive.appManager.domain.DataScopeBase;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.detection.domain.InspectionLogs;
import cn.yuanqiao.archive.detection.domain.InspectionRecords;
import cn.yuanqiao.archive.detection.mapper.InspectionLogsMapper;
import cn.yuanqiao.archive.detection.mapper.InspectionRecordsMapper;
import cn.yuanqiao.archive.detection.service.IInspectionRecordsService;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 四性检测记录Service业务层处理
 *
 * @author xy
 * @date 2023-08-07
 */
@Service
public class InspectionRecordsServiceImpl implements IInspectionRecordsService
{
    private static final Logger log = LoggerFactory.getLogger(InspectionRecordsServiceImpl.class);

    @Autowired
    private InspectionRecordsMapper inspectionRecordsMapper;
    @Autowired
    private InspectionLogsMapper inspectionLogsMapper;
    @Autowired
    private ITenantSysConfigService sysConfigService;

    /**
     * 查询四性检测记录
     *
     * @param id 四性检测记录主键
     * @return 四性检测记录
     */
    @Override
    public InspectionRecords selectInspectionRecordsById(Long id)
    {
        return inspectionRecordsMapper.selectInspectionRecordsById(id,new InspectionRecords().getTableName());
    }

    /**
     * 查询四性检测记录列表
     *
     * @param inspectionRecords 四性检测记录
     * @return 四性检测记录
     */
    @Override
    public List<InspectionRecords> selectInspectionRecordsList(InspectionRecords inspectionRecords)
    {
        return inspectionRecordsMapper.selectInspectionRecordsList(new DataScopeBase(),inspectionRecords);
    }

    /**
     * 新增四性检测记录
     *
     * @param inspectionRecords 四性检测记录
     * @return 结果
     */
    @Override
    public int insertInspectionRecords(InspectionRecords inspectionRecords)
    {
        inspectionRecords.setIsDel(0);
        return inspectionRecordsMapper.insertInspectionRecords(inspectionRecords);
    }

    /**
     * 修改四性检测记录
     *
     * @param inspectionRecords 四性检测记录
     * @return 结果
     */
    @Override
    public int updateInspectionRecords(InspectionRecords inspectionRecords)
    {
        return inspectionRecordsMapper.updateInspectionRecords(inspectionRecords);
    }

    /**
     * 批量删除四性检测记录
     *
     * @param ids 需要删除的四性检测记录主键
     * @return 结果
     */
    @Override
    public int deleteInspectionRecordsByIds(Long[] ids)
    {
        return inspectionRecordsMapper.deleteInspectionRecordsByIds(ids,new InspectionRecords().getTableName());
    }

    /**
     * 删除四性检测记录信息
     *
     * @param id 四性检测记录主键
     * @return 结果
     */
    @Override
    public int deleteInspectionRecordsById(Long id)
    {
        return inspectionRecordsMapper.deleteInspectionRecordsById(id);
    }

    @Override
    public String zipExport(InspectionRecords inspectionRecords) {
        //获取值并进行打包
        InspectionRecords inspectionRecords1=inspectionRecordsMapper.selectInspectionRecordsById(inspectionRecords.getId(),inspectionRecords.getTableName());
        Document dast = createTitleXml(inspectionRecords1);
        //生成文件
        String xmlPath=sysConfigService.selectConfigByKey("XML_PATH");
        if(StringUtils.isEmpty(xmlPath)){
            throw new ServiceException("系统参数错误XML_PATH未找到配置！");
        }
        String path="";
       // writer(path,dast);
        try {
           path= writer(xmlPath, dast);
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return path;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean xmlImportData(MultipartFile file) {
        try{
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            InputStreamReader o = new InputStreamReader(file.getInputStream());
            String xml = org.apache.commons.io.IOUtils.toString(o);
            net.sf.json.xml.XMLSerializer xmlSerializer = new net.sf.json.xml.XMLSerializer();
            net.sf.json.JSONObject json = (net.sf.json.JSONObject) xmlSerializer.read(xml);
            o.close();
            //对json进行获取值
            JSONObject jsonObject=json.getJSONObject("四性检测记录");
            InspectionRecords inspectionRecords=new InspectionRecords();
            Long id= SnowflakeIdGenerator.generateId();
            inspectionRecords.setId(id);
            String link=jsonObject.getString("检测阶段");
            if(!StringUtils.isEmpty(link)){
                if(link.equals("归档阶段")){
                    link="0";
                }else if(link.equals("移交阶段")){
                    link="1";
                }else if(link.equals("长期阶段")){
                    link="2";
                }

            }
            inspectionRecords.setDetectionLink(link);
            String result= jsonObject.getString("检测结果");
            if(!StringUtils.isEmpty(result)){
                if(result.equals("通过")){
                    result="1";
                }else if(result.equals("不通过")){
                    result="0";
                }
            }
            inspectionRecords.setDetectionResult(result);
            String time=jsonObject.getString("检测时间");
            if(!StringUtils.isEmpty(time)){
                inspectionRecords.setDetectionTime(sdf.parse(time));
            }
            String categoryId=jsonObject.getString("检测门类");
            if(!StringUtils.isEmpty(categoryId)){
                inspectionRecords.setCategoryId(Long.valueOf(categoryId));
            }
            String dh=jsonObject.getString("检测档号");
            if(!StringUtils.isEmpty(dh)){
                inspectionRecords.setDetectionDh(dh);
            }
            inspectionRecords.setIsDel(0);
            inspectionRecordsMapper.insertInspectionRecords(inspectionRecords);
            //获取值
            JSONArray jsonObj = json.getJSONArray("检测结果");
            for(Object ob:jsonObj){
                JSONObject js= (JSONObject) ob;
                InspectionLogs inspectionLogs=new InspectionLogs();
                inspectionLogs.setpId(id);
                String jcnr=js.getString("检测内容");
                if(!StringUtils.isEmpty(jcnr)) {
                    Long dId = inspectionLogsMapper.getDetectionDid(jcnr);
                    inspectionLogs.setdId(dId);
                }
                String jcjg=js.getString("检测结果");
                if(!StringUtils.isEmpty(jcjg)){
                    if(jcjg.equals("通过")){
                        jcjg="1";
                    }else if(jcjg.equals("不通过")){
                        jcjg="0";
                    }
                }
                inspectionLogs.setDetectionResult(jcjg);
                String jcsj=js.getString("检测时间");
                if(!StringUtils.isEmpty(jcsj)){
                    inspectionLogs.setDetectionTime(sdf.parse(jcsj));
                }
                String sbsl=js.getString("失败数量");
                if(!StringUtils.isEmpty(sbsl)){
                    inspectionLogs.setFailNum(sbsl);
                }
                inspectionLogsMapper.insertInspectionLogs(inspectionLogs);

            }


            return true;
        }catch (Exception ex){
            log.error("导入失败！", ex.getMessage());
            return false;
        }

    }

    private Document createTitleXml( InspectionRecords inspectionRecords){
        Document document = DocumentHelper.createDocument();

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Element root = document.addElement("四性检测");
        Element jl=root.addElement("四性检测记录");
        String link=inspectionRecords.getDetectionLink();

        if(link.equals("0")){
            link="归档阶段";
        }else if(link.equals("1")){
            link="移交阶段";
        }else if(link.equals("2")){
            link="长期阶段";
        }else if(link.equals("4")){
            link="预归档";
        }
        String result=inspectionRecords.getDetectionResult();
        if(result.equals("0")){
            result="不通过";
        }else if(result.equals("1")){
            result="通过";
        }

        jl.addElement("检测阶段").addText(link);
        jl.addElement("检测结果").addText(result);
        jl.addElement("检测时间").addText(inspectionRecords.getDetectionTime()==null?"":sdf.format(inspectionRecords.getDetectionTime()));
        jl.addElement("检测门类").addText(inspectionRecords.getCategoryId().toString());
        jl.addElement("检测档号").addText(inspectionRecords.getDetectionDh()==null?"":inspectionRecords.getDetectionDh());
        Element jg=root.addElement("检测结果");
        //获取全部的检测项
        InspectionLogs in=new InspectionLogs();
        in.setpId(inspectionRecords.getId());
        List<InspectionLogs> inspectionLogsList=inspectionLogsMapper.selectInspectionLogsList(in);
        for(InspectionLogs inspectionLogs:inspectionLogsList){
            //遍历
            Element jcx=jg.addElement("检测项");
            //通过id获取到内容
            String jcnr=inspectionLogsMapper.getDetectionContent(inspectionLogs.getdId());
            jcx.addElement("检测内容").addText(jcnr);
            String jcjg=inspectionLogs.getDetectionResult();
            if(jcjg.equals("0")){
                jcjg="不通过";
            }else if(jcjg.equals("1")){
                jcjg="通过";
            }
            jcx.addElement("检测结果").addText(jcjg);
            jcx.addElement("检测时间").addText(sdf.format(inspectionLogs.getDetectionTime()));
            jcx.addElement("失败数量").addText(inspectionLogs.getFailNum()==null?"":inspectionLogs.getFailNum());
        }

        return document;
    }

    /**
     * 写入文件
     * @param path
     * @param document
     * @throws IOException
     */
    public String writer(String path,Document document) throws IOException {
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        // 紧凑的格式
        // OutputFormat format = OutputFormat.createCompactFormat();
        // 排版缩进的格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        // 设置编码
        format.setEncoding("UTF-8");
        // 创建XMLWriter对象,指定了写出文件及编码格式
        // XMLWriter writer = new XMLWriter(new FileWriter(new
        // File("src//a.xml")),format);
        path+=new Date().getTime()+".xml";
        XMLWriter writer = new XMLWriter(
                new OutputStreamWriter(new FileOutputStream(new File(path)), "UTF-8"), format);
        // 写入
        writer.write(document);
        // 立即写入
        writer.flush();
        // 关闭操作
        writer.close();
        return path;
    }
}
